<?php


namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Partner\Partner;
use App\Models\Partner\PartnerUser;
use App\Models\User;
use Endroid\QrCode\QrCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Vinkla\Hashids\Facades\Hashids;
use Illuminate\Support\Facades\Storage;

class UserController extends Controller
{

    public function info(Request $request){

        $partner = new Partner();
        $partnerUser = new PartnerUser();
        $user = $this->userInfo();
        if($user->status == 0){
            return $this->ajaxError('該用戶異常請聯係客服');
        }
        if($user){
            $user = $user->toArray();
        }
        $partnerName = DB::table("{$partnerUser->getTable()} as pu")
            ->join("{$partner->getTable()} as p","p.id","=","pu.partner_id")
            ->where('pu.user_id',$user['id'])
            ->select('p.name','pu.partner_id')->first();
        $user['partner_name'] = !empty($partnerName) ? $partnerName->name : "普通用戶";
        $user['partner_id'] = !empty($partnerName) ? $partnerName->partner_id : 0;
        if($user){
            return $this->ajaxSuccess($user);
        }else{
            return $this->ajaxError('token爲空或用戶信息獲取失敗');
        }

    }


    public function editName(Request $request){

        $name = $request->post('nickname');
        $user = $this->userInfo();
        $user->nickname = $name;
        $user->save();
        return $this->ajaxSuccess([]);

    }


    public function avatar(Request $request){

        $current_user = $this->userInfo();
        $current_user = User::where('id',$current_user->id)->first();
        $image = $request->file('image');
        list ($width, $height, $type) = getimagesize($image->path());
        $current_user->avatar = [
            'image' => preg_replace('#^public/#', '', $image->storePublicly('public/avatar')),
            'width' => $width,
            'height' => $height,
            'mime' => image_type_to_mime_type($type)
        ];
        $current_user->save();
        if($current_user){
            return $this->ajaxSuccess($current_user->avatar);
        }else{
            return  $this->ajaxError();
        }

    }


    public function inviteData(){

        $current_user = $this->userInfo();
        $inviteCode = Hashids::encode($current_user->id + 100000);
        $inviteData = $current_user->toArray();

        $downloadUrl = env('APP_URL');
        $shareBg = 'img/share.jpg';
        $inviteData['InvitedURL'] = $downloadUrl.'/?ref=' . $inviteCode;
        $inviteData['InvitedCode'] =  Hashids::encode($current_user->id + 100000);

        $directory = "public/qrcode/invite";
        $filename = "{$inviteCode}_v2.jpg";
        $path = storage_path("app/{$directory}/{$filename}");
        $exists = Storage::exists("{$directory}/{$filename}");
        if (! $exists) {

            $qrcode = new QrCode();
            $qrcode->setText($inviteData['InvitedURL']);
            $qrcode->setSize(260);
            $qrcode->setMargin(0);
            $qrcode->setLogoWidth(40);

            Storage::makeDirectory($directory);
            $qrcode->writeFile($path);
        }

        $synthetic_img_filename = "{$inviteCode}_v2_ad.jpg";

        $inviteData['inviteImg'] = env('APP_DOWNLOAD_URL').preg_replace('#^public/#', '/storage/', "{$directory}/{$synthetic_img_filename}");
        if($inviteData){
            return $this->ajaxSuccess($inviteData);
        }else{
            return $this->ajaxError();
        }

    }


    public function editPassword(Request $request){

        $data = $this->decryptData($request->post());
        $user = $this->userInfo();

        if($data['new_password'] != $data['new_password_confirmation']){
            return $this->ajaxError('兩次輸入密碼不一致');
        }
        $code = Cache::store('redis')->get('email'.$user->username);
        if($code != $data['smsverify']){
            return $this->ajaxError('郵箱驗證碼錯誤');
        }

        if(!password_verify($data['old_password'],$user->password)){
            return  $this->ajaxError("輸入的舊密碼不正確請重新輸入");
        }
        $user->password = password_hash($data['new_password'],PASSWORD_DEFAULT);
        $user->save();
        if($user){
            return $this->ajaxSuccess([]);
        }else{
            return $this->ajaxError();
        }


    }


    public function editSecondaryPassword(Request $request){

        $data = $this->decryptData($request->post());

        $user = $this->userInfo();

        if($data['new_password'] != $data['new_password_confirmation']){
            return $this->ajaxError('兩次輸入密碼不一致');
        }
        $code = Cache::store('redis')->get('email'.$user->username);
        if($code != $data['smsverify']){
            return $this->ajaxError('郵箱驗證碼錯誤');
        }
        if(!password_verify($data['old_password'],$user->password)){
            return  $this->ajaxError("輸入的舊密碼不正確請重新輸入");
        }
        $user->secondary_password = password_hash($data['new_password'],PASSWORD_DEFAULT);
        $user->save();
        return $this->ajaxSuccess([]);

    }

}
